import logging

from app.service import app_jwt_auth
from libs.app_helper import resp_error
from libs.auth import jwt_decode
from libs.common import error

logger = logging.getLogger(__name__)


def jwt_auth(func):
    def decorator(request, *args, **kwargs):
        try:
            token = str(request.headers.get('token'))
            payload = jwt_decode(token)
            cashier_id = payload.get('cashier_id', '')
            shop_id = payload.get('shop_id', '')
            if cashier_id == '' or shop_id == '':
                return error('token参数错误', status=401)
            auth = {
                'cashier_id': cashier_id,
                'shop_id': shop_id
            }
        except Exception as e:
            logger.info(e.args)
            return error('token参数错误', status=401)
        return func(request, auth=auth, *args, **kwargs)

    return decorator


def app_auth_hook(func):
    def decorator(request, *args, **kwargs):
        try:
            token = str(request.headers.get('token'))
            payload = app_jwt_auth.jwt_decode(token)
            member_id = payload.get('member_id', '')
            auth = {
                'member_id': member_id,
            }
        except Exception as e:
            logger.info(e.args)
            return resp_error('token参数错误')
        return func(request, auth=auth, *args, **kwargs)

    return decorator
